package com.my.aslife.aop;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import com.my.aslife.exception.BusinessException;
import com.my.aslife.module.common.Constant;
import com.my.aslife.module.common.ErrorCode;
import com.my.aslife.module.entity.User;
import com.my.aslife.module.entity.dtos.RegisterDto;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
@Slf4j
public class AddNickNameAndAvatarAop {

    @Around("execution(* com.my.aslife.service.impl.UserServiceImpl.register*(..))")
    public Object addNiceName(ProceedingJoinPoint pjp) throws Throwable {
        log.info("对象转换");
        User user = null;
        Object object = pjp.getArgs()[0];
        if (object instanceof User) {
            log.info("转换为 user");
            user = (User) object;
        } else if (object instanceof RegisterDto) {
            log.info("转换为 registerDto");
            user = ((RegisterDto) object).getUser();
        }

        if (user == null) {
            throw new BusinessException(ErrorCode.ERROR_ADD_NIKENAME_AVATAR);
        }

        user.setNickName("AS_" + RandomUtil.randomString(10));
        user.setAvatarUrl(Constant.AVATAR_URL);
        user.setPwdUpdateTime(LocalDateTimeUtil.now());
        user.setCreateTime(LocalDateTimeUtil.now());
        user.setLoginTime(LocalDateTimeUtil.now());
        Object proceed = pjp.proceed();

        return proceed;
    }


}
